//
//  EFSTopBannerView.m
//  EFSMobile
//
//  Created by Chuan on 11/30/15.
//  Copyright © 2015 Elephants Financial Service. All rights reserved.
//

#import "EFSTopBannerView.h"
#import "EFSTopBannerCell.h"
#import "EFSTopBannerManager.h"
//#import "Masonry.h"
//#import "EFSJump.h"

#define kTopBannerScrollCount (10 * (NSInteger)_bannerList.count)

@interface EFSTopBannerView() <UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UIScrollViewDelegate>

@property (strong, nonatomic) UICollectionView * bannerCollectionView;
@property (strong, nonatomic) UIPageControl * pageControl;
@property (strong, nonatomic) RACSubject * stopSignal;

@end

@implementation EFSTopBannerView

- (UICollectionView *)bannerCollectionView {
    if (!_bannerCollectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        [flowLayout setMinimumInteritemSpacing:0.f];
        [flowLayout setMinimumLineSpacing:0.f];
//        [flowLayout setItemSize:self.size];
        
        _bannerCollectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:flowLayout];
        _bannerCollectionView.delegate = self;
        _bannerCollectionView.dataSource = self;
        _bannerCollectionView.pagingEnabled = YES;
        _bannerCollectionView.scrollsToTop = NO;
        _bannerCollectionView.backgroundColor = [UIColor clearColor];
        _bannerCollectionView.showsHorizontalScrollIndicator = NO;
        _bannerCollectionView.translatesAutoresizingMaskIntoConstraints = NO;
        
        [_bannerCollectionView registerClass:[EFSTopBannerCell class] forCellWithReuseIdentifier:@"EFSTopBannerCell"];
    }
    return _bannerCollectionView;
}

- (UIPageControl *)pageControl
{
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc] init];
        RAC(_pageControl,numberOfPages) = [RACObserve(self,bannerList) map:^id(id value) {
            return @(self.bannerList.count);
        }];
//        _pageControl.currentPageIndicatorTintColor = [UIColor colorFromHexString:@"c7000a"];
//        _pageControl.pageIndicatorTintColor = [UIColor colorFromHexString:@"bfbbb8"];
        _pageControl.translatesAutoresizingMaskIntoConstraints = NO;
        _pageControl.alpha = 0.6;
    }
    return _pageControl;
}

- (RACSubject *)stopSignal {
    if (!_stopSignal) {
        _stopSignal = [RACSubject subject];
    }
    return _stopSignal;
}

- (void)setBannerList:(NSArray *)bannerList {
    _bannerList = bannerList;
    if (bannerList.count) {
        [self resetCollectionView];
    }
}

- (void)resetCollectionView
{
    [self resetCollectionViewOffset:0];
    [_bannerCollectionView reloadData];
}

- (void)resetCollectionViewOffset:(NSInteger)offset
{
//    [_bannerCollectionView setContentOffset:CGPointMake((kTopBannerScrollCount / 2 + offset) * self.width, 0) animated:NO];
    _pageControl.currentPage = offset;
}

- (BOOL)resetCollectionViewWithCurrentIndex:(NSInteger)currentIndex
{
    BOOL isBegin = currentIndex <= _bannerList.count*4;
    BOOL isEnd = (currentIndex >= (kTopBannerScrollCount - _bannerList.count*4)) && (currentIndex <= kTopBannerScrollCount);
    if (isBegin || isEnd) {
        [self resetCollectionViewOffset:(currentIndex % (_bannerList.count))];
        return YES;
    }
    return NO;
}

- (void)awakeFromNib {
    
    [super awakeFromNib];
    [self addSubview:self.bannerCollectionView];
    [self addSubview:self.pageControl];
    // 与父容器相同大小
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[_bannerCollectionView]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_bannerCollectionView)]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[_bannerCollectionView]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_bannerCollectionView)]];
    
//    [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.bottom.mas_equalTo(8);
//        make.right.mas_equalTo(-9);
//    }];

    // 控制滑动时禁止动画
    @weakify(self);
    [[self rac_signalForSelector:@selector(scrollViewWillBeginDragging:) fromProtocol:@protocol(UIScrollViewDelegate)] subscribeNext:^(id x) {
        @strongify(self);
        [self stopBannerScrolling];
    }];
    [[self rac_signalForSelector:@selector(scrollViewWillEndDragging:withVelocity:targetContentOffset :) fromProtocol:@protocol(UIScrollViewDelegate)] subscribeNext:^(id x) {
        @strongify(self);
        [self startBannerScrolling];
    }];
}

#pragma mark - Collection Biew Delegate
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.bannerList.count) {
        EFSTopBannerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EFSTopBannerCell" forIndexPath:indexPath];
        [cell configCell:_bannerList[[self currentIndexWithScrollIndex:indexPath.item]]];
        return cell;
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

    return CGSizeMake(0, 0);
//    return (self.bannerList && self.bannerList.count) ? self.size : CGSizeZero;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return (self.bannerList && self.bannerList.count) ? kTopBannerScrollCount : 0;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsZero;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
        NSDictionary *itemDict = _bannerList[[self currentIndexWithScrollIndex:indexPath.item]];
//        [EFSJump jump:JumpTypeActivity withData:itemDict from:[UIViewController visibleViewController]];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSIndexPath *currentIndexPath = [self.bannerCollectionView indexPathForItemAtPoint:[self convertPoint:self.bannerCollectionView.center toView:self.bannerCollectionView]];
    _pageControl.currentPage = [self currentIndexWithScrollIndex:currentIndexPath.item];
    [self resetCollectionViewWithCurrentIndex:currentIndexPath.item];
}

#pragma mark - Banner Control
- (void)launch {
    if (_bannerList == nil) {
        self.bannerList = [[EFSTopBannerManager sharedManager] loadTopBanner];
    }
    
    @weakify(self);
    [[[EFSTopBannerManager sharedManager] fetchTopBanner] subscribeNext:^(id x) {
        @strongify(self);
        self.bannerList = x;
        [[EFSTopBannerManager sharedManager] saveTopBanner:x];
    } error:^(NSError *error) {
        NSLog(@"TopBanner: 获取数据失败");
    }];
}

- (void)startBannerScrolling {
    @weakify(self);
//    [[[[[[RACSignal interval:5 onScheduler:[RACScheduler mainThreadScheduler]] startWith:[NSDate now]] skip:1] takeUntil:self.stopSignal] filter:^BOOL(id value) {
//        @strongify(self);
//        return self.bannerList && self.bannerList.count > 0;
//    }] subscribeNext:^(id x) {
//        @strongify(self);
//        NSIndexPath *currentIndexPath = [self.bannerCollectionView indexPathForItemAtPoint:[self convertPoint:self.bannerCollectionView.center toView:self.bannerCollectionView]];
//        if ([self resetCollectionViewWithCurrentIndex:currentIndexPath.item]) {
//            currentIndexPath = [self.bannerCollectionView indexPathForItemAtPoint:[self convertPoint:self.bannerCollectionView.center toView:self.bannerCollectionView]];
//        }
//        NSInteger nextItem = (currentIndexPath.item + 1);
//        _pageControl.currentPage = [self currentIndexWithScrollIndex:nextItem];
//        
//        [self.bannerCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:nextItem inSection:currentIndexPath.section] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
//    }];
}

- (NSInteger)currentIndexWithScrollIndex:(NSInteger)scrollIndex
{
    if (!_bannerList || _bannerList.count == 0) {
        return 0;
    }
    NSInteger count = _bannerList.count;
    NSInteger tmp = (scrollIndex - kTopBannerScrollCount/2) % count;
    return tmp >= 0 ? tmp : tmp + count;
}

- (void)stopBannerScrolling {
    [self.stopSignal sendNext:nil];
}

@end
